/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sbmart.smartserver.task;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.SQLExec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sbmart.object.Header;
import sbmart.util.Ping;

/**
 *
 * @author albert
 *
 */
public class ClientQueryTask implements Runnable {

    private List<Header> headers = new ArrayList<Header>();
    public static final Logger LOG = LoggerFactory.getLogger("ClientQuery");
    private ExecutorService exec;
    private static final String sqlFilePath = "../query_exec_per_hour.sql";

    public ClientQueryTask(List<Header> headers, ExecutorService exec) {
        this.headers = headers;
        this.exec = exec;
    }

    @Override
    public void run() {
        LOG.info("<RUN> " + getClass().getSimpleName());
        for (Header header : headers) {
            LOG.debug( header.getBranchId() +"|"+header.getBranchName() + "|" + header.getIpaddress());
            try {
                if (!Ping.isReachable(header.getIpaddress())) {
                    LOG.error("[ERROR] connection is not reachable : " +  header.getBranchId() + ". " + header.getBranchName() + " " +header.getNickname() + " - " + header.getIpaddress());
                    continue;
                }
                upadateStoreProcedure(header);
            } catch (Exception ex) {
                LOG.error("<ERROR> : " +  header.getBranchId() + ". " + header.getBranchName() + " " +header.getNickname() + " - " + header.getIpaddress(), ex);
            } finally {
                continue;
            }
        }
        LOG.info("<END> upadateStoreProcedure" + getClass().getSimpleName());
    }

    private void upadateStoreProcedure(Header header) throws Exception {
        LOG.info("[CALL] " +  header.getBranchId() + ". " + header.getBranchName() + " " +header.getNickname() + " - " + header.getIpaddress());
        SqlExecuter executer = new SqlExecuter();
        executer.setSrc(new File(sqlFilePath));
        executer.setDriver("net.sourceforge.jtds.jdbc.Driver");
        executer.setUserid(header.getUsername());
        executer.setPassword(header.getPassword());
        executer.setDelimiter("GO");
        executer.setKeepformat(true);
        executer.setUrl("jdbc:jtds:sqlserver://" + header.getIpaddress() + ":1433/sbmart_gerai");
        executer.execute();
        LOG.info("<COMMIT> " +  header.getBranchId() + ". " + header.getBranchName() + " " +header.getNickname() + " - " + header.getIpaddress()+"\n");

    }

    final class SqlExecuter extends SQLExec {

        public SqlExecuter() {
            Project project = new Project();
            project.init();
            setProject(project);
            setTaskType("sql");
            setTaskName("SQL Init");
        }
    }
}
